package com.insleton.admin.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 资源配置
 * <p>
 *     1、静态资源映射，让tomcat处理图片信息
 * </p>
 * <p>
 *     2、允许跨域的配置
 * </p>
 */
@Configuration
public class ResourcesConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射类路径下的静态资源
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static" + File.separator);

        // 也可以映射多个路径
        // registry.addResourceHandler("/static/**", "/svgx/**")
        //         .addResourceLocations("file:D:/static" + File.separator,
        //                 "classpath:/static" + File.separator + "svgx" + File.separator);
    }

    /**
     * 配置跨域支持
     * @param registry 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")        // 允许的路径，即我们那些接口可以跨域
                // java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead
                .allowedOriginPatterns("*")        // 允许的源，这个是ant匹配符，和allowedOrigins是不一样的
                // .allowedOrigins()
                .allowCredentials(true)    // 是否允许发送凭证，cookie
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")  // 指定允许的 HTTP 方法
                .maxAge(3600 * 24);        //预检请求有效期
    }
}
